/*
 * @Author: hongbin
 * @Date: 2023-10-12 15:35:24
 * @LastEditors: hongbin
 * @LastEditTime: 2023-10-18 10:22:30
 * @Description: Personnel
 */
import { model } from "mongoose";
import { PersonnelSchema } from "../Schema/index.js";
import { Manager } from "./index.js";
import { ObjectId } from "mongodb";

export const PersonnelModel = model("personnel", PersonnelSchema);
export class PersonnelManager extends Manager {
  model = PersonnelModel;

  constructor(app) {
    super(model);
    this.app = app;
    this.listen(app);

    // const newItem = new PersonnelModel({
    //   creator: new ObjectId("652cac61f4360ac68defd596"),
    //   title: "VUE",
    //   order: 0,
    // });
    // newItem
    //   .save({ checkKeys: true })
    //   .then(res => {
    //     console.log("res", res);
    //   })
    //   .catch(err => {
    //     console.log("err", err);
    //   });
  }

  listen(app) {
    app.post("/user/login", async (req, res) => {
      console.log("payload:", req.payload);
      this.findOne(req.payload)
        .then(data => {
          console.log("data", data);
          if (data) res.json(data);
          else res.status(555).json({ msg: "登陆失败" });
        })
        .catch(err => {
          res.status(555).json({ msg: "登陆失败" });
        });
    });
    app.post("/user/insert", async (req, res) => {
      req.payload.roleIds = req.payload.roleIds.map(id => new ObjectId(id));
      // console.log("payload:", req.payload);
      this.create(req.payload)
        .then(r => {
          if (r) res.json(r);
          else res.status(555).json({ msg: "获取失败" });
        })
        .catch(err => {
          res.status(555).json({ msg: "创建失败" });
        });
    });
    app.get("/user/list", async (req, res) => {
      this.findAll()
        .then(r => {
          if (r) res.json(r);
          else res.status(555).json({ msg: "获取失败" });
        })
        .catch(err => {
          res.status(555).json({ msg: "获取失败" });
        });
    });
    app.post("/user/delete", async (req, res) => {
      const filter = {
        _id: { $in: req.payload.ids.map(id => new ObjectId(id)) },
      };
      console.log(filter._id.$in);
      this.deleteMany(filter)
        .then(r => {
          console.log(r);
          if (r) res.json(r);
          else res.status(555).json({ msg: "操作失败" });
        })
        .catch(err => {
          console.log(err);
          res.status(555).json({ msg: "操作失败" });
        });
    });
  }
}
